package io.renren.modules.sys.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import io.renren.common.utils.Constant;
import io.renren.modules.sys.dao.MenuDao;
import io.renren.modules.sys.dao.UserDao;
import io.renren.modules.sys.dao.UserTokenDao;
import io.renren.modules.sys.entity.Menu;
import io.renren.modules.sys.entity.User;
import io.renren.modules.sys.entity.UserToken;
import io.renren.modules.sys.service.ShiroService;

@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private UserTokenDao userTokenDao;

    @Override
    public Set<String> getUserPermissions(String userId) {
        List<String> permsList ;

        //系统管理员，拥有最高权限
        if(Constant.SUPER_ADMIN.equals(userId)){
            List<Menu> menuList = menuDao.selectList(null);
            permsList = new ArrayList<>(menuList.size());
            for(Menu menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = userDao.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public UserToken queryByToken(String token) {
        return userTokenDao.queryByToken(token);
    }

    @Override
    public User queryUser(String userId) {
        return userDao.selectById(userId);
    }
}
